import 'dart:io';
import 'dart:ui';

import 'package:flutter/foundation.dart';
import 'package:flutter_common/util/string_utils.dart';

extension FileExtension on FileSystemEntity {

  ///获取文件名称
  String name() {
    List<String> p = path.split('/');
    return p.lastWhere((element) => element.isNotEmpty, orElse: () => '');
  }

  ///获取文件的扩展名
  String get ext => path.ext;

  ///获取目标文件的大小
  static int getFileSize(FileSystemEntity root) {
    if (!root.existsSync()) return 0;
    if (FileSystemEntity.isFileSync(root.path)) {
      return (root as File).lengthSync();
    }

    List<FileSystemEntity> file = (root as Directory).listSync();
    int sum = 0;
    for (FileSystemEntity f in file) {
      if (FileSystemEntity.isDirectorySync(f.path)) {
        sum += getFileSize(f);
      } else if(FileSystemEntity.isFileSync(f.path)){
        sum += (f as File).lengthSync();
      } else {
        if(kDebugMode) print("getFileSize file runtimeType ${f.runtimeType} ${f.path}");
      }
    }
    return sum;
  }

  ///获取文件大小
  ///
  ///[fractionDigits] 保留小数点后几位， 0 <= fractionDigits <= 20
  static String formatFileSize(
      {FileSystemEntity? file, int? size, int fractionDigits = 2}) {
    assert(fractionDigits >= 0);
    assert(fractionDigits <= 20);

    int? s = file == null ? size : getFileSize(file);
    return _formatSize(s ?? 0, fractionDigits);
  }

  static String _formatSize(int size, int fractionDigits) {
    double result = size.toDouble();
    String suffix = "B";
    if (result > 900) {
      suffix = "KB";
      result = result / 1024;
    }
    if (result > 900) {
      suffix = "MB";
      result = result / 1024;
    }
    if (result > 900) {
      suffix = "GB";
      result = result / 1024;
    }
    if (result > 900) {
      suffix = "TB";
      result = result / 1024;
    }
    if (result > 900) {
      suffix = "PB";
      result = result / 1024;
    }
    String s = result.toStringAsFixed(fractionDigits);
    return "$s$suffix";
  }

  ///@param root 根目录
  ///
  /// @param deleteRoot 是否删除[root]目录
  static Future<void> deleteChildFiles(Directory root, bool deleteRoot) async {
    bool exists = await root.exists();
    if (!exists) {
      return;
    }
    await root.list().forEach((element) async {
      //如果文件夹内有文件，则删除文件夹报错 (OS Error: Directory not empty, errno = 39)
      await delete(element);
    }).whenComplete(() {
      if (deleteRoot) {
        //不可对系统目录 删除 否则报错 如 /data/user/0/com.enotary.tianxin/cache
        root.delete();
      }
    });
  }

  /// 递归删除缓存目录和文件
  static Future<void> delete(FileSystemEntity file) async {
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      for (final FileSystemEntity child in children) {
        await delete(child);
      }
      await file.delete();
    } else if(file.existsSync()) {
        await file.delete();
    }
  }
}

extension ColorExtension on Color {

  ///追加百分比透明度
  /// [percent] 范围[0.0,1.0]
  Color withPercentAlpha(double percent) {
    if(percent <= 0) return const Color(0x00000000);

    int a = (percent * 255).toInt();
    return withAlpha(a < 255 ? a : 255);
  }
}